﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Localization;

namespace SBPweb.DNN.PhotoGallery
{
    public partial class EditPhotoGalleryViewer : DotNetNuke.Entities.Modules.PortalModuleBase
    {

        public PhotoGalleryInfo PhotoGallery
        {
            get
            {
                return Session[this.ClientID + "_PhotoGallery"] as PhotoGalleryInfo;
            }
            set
            {
                Session[this.ClientID + "_PhotoGallery"] = value;
            }
        }

        private void Page_Load(object sender, System.EventArgs e)
        {
            if ((Page.IsPostBack == false))
            {
                cmdDelete.Attributes.Add("onClick", ("javascript:return confirm(\'" + (Localization.GetString("DeleteItem") + "\');")));
                PhotoGallery = PhotoGalleryController.GetPhotoGallery(null, ModuleId);
                if (!(PhotoGallery == null))
                {
                    PhotoGallery.AddRange(PhotoGallerySlideController.GetPhotoGallerySlides(PhotoGallery.PhotoGalleryId));
                    PhotoGallery.Sort();
                    repSlides.DataSource = PhotoGallery;
                    repSlides.DataBind();
                    ctlAudit.CreatedDate = PhotoGallery.CreatedDate.ToShortDateString();
                }
                else
                {
                    // security violation attempt to access item not related to this Module
                    Response.Redirect(Globals.NavigateURL());
                }
            }
        }

        protected void repSlides_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                PhotoGallerySlideInfo item = e.Item.DataItem as PhotoGallerySlideInfo;
                TextBox tbCaption = e.Item.FindControl("txtCaption") as TextBox;
                TextBox tbImage = e.Item.FindControl("txtImageUrl") as TextBox;
                TextBox tbThumb = e.Item.FindControl("txtThumbUrl") as TextBox;
                TextBox tbScale = e.Item.FindControl("txtScale") as TextBox;
                TextBox tbRotation = e.Item.FindControl("txtRotation") as TextBox;
                TextBox tbCenterX = e.Item.FindControl("txtCenterX") as TextBox;
                TextBox tbCenterY = e.Item.FindControl("txtCenterY") as TextBox;
                TextBox tbDuration = e.Item.FindControl("txtDuration") as TextBox;
                TextBox tbEndDelay = e.Item.FindControl("txtEndDelay") as TextBox;
                Image imgImage = e.Item.FindControl("imgImage") as Image;
                Image imgThumb = e.Item.FindControl("imgThumb") as Image;
                DropDownList ddlIndex = e.Item.FindControl("ddlIndex") as DropDownList;
                tbCaption.Text = item.Caption;
                tbCaption.Attributes["index"] = item.OrderIndex.ToString();
                tbImage.Text = item.Image.OriginalString;
                tbImage.Attributes["index"] = item.OrderIndex.ToString();
                tbThumb.Text = item.Thumbnail.OriginalString;
                tbThumb.Attributes["index"] = item.OrderIndex.ToString();
                imgImage.ImageUrl = GetImageLocation(item.Image);
                if (item.Thumbnail != null)
                {
                    imgThumb.ImageUrl = GetImageLocation(item.Thumbnail);
                }
                if (item.Scale.HasValue)
                {
                    tbScale.Text = item.Scale.Value.ToString();
                }
                if (item.RotateAngle.HasValue)
                {
                    tbRotation.Text = item.RotateAngle.Value.ToString();
                }
                if (item.CenterX.HasValue)
                {
                    tbCenterX.Text = item.CenterX.Value.ToString();
                }
                if (item.CenterY.HasValue)
                {
                    tbCenterY.Text = item.CenterY.Value.ToString();
                }
                InitIndexDropDown(ddlIndex, PhotoGallery.Count);
                ddlIndex.SelectedIndex = item.OrderIndex;
                ddlIndex.Attributes["index"] = item.OrderIndex.ToString();
            }
        }

        protected void txt_TextChanged(object sender, EventArgs e)
        {
            TextBox txt = sender as TextBox;
            Image imgImage = txt.Parent.FindControl("imgImage") as Image;
            Image imgThumb = txt.Parent.FindControl("imgThumb") as Image;
            int index = Convert.ToInt32(txt.Attributes["index"]);
            PhotoGallerySlideInfo slide = PhotoGallery[index];
            switch (txt.ID)
            {
                default:
                    break;
                case "txtCaption":
                    slide.Caption = txt.Text;
                    break;
                case "txtImageUrl":
                    slide.Image = new Uri(txt.Text, UriKind.Relative);
                    imgImage.ImageUrl = GetImageLocation(slide.Image);
                    break;
                case "txtThumbUrl":
                    slide.Thumbnail = new Uri(txt.Text, UriKind.Relative);
                    imgThumb.ImageUrl = GetImageLocation(slide.Thumbnail);
                    break;
                case "txtScale":
                    slide.Scale = Convert.ToDouble(txt.Text);
                    break;
                case "txtRotation":
                    slide.RotateAngle = Convert.ToDouble(txt.Text);
                    break;
                case "txtCenterX":
                    slide.CenterX = Convert.ToDouble(txt.Text);
                    break;
                case "txtCenterY":
                    slide.CenterY = Convert.ToDouble(txt.Text);
                    break;
                case "txtDuration":
                    slide.Duration = Convert.ToInt32(txt.Text);
                    break;
                case "txtEndDelay":
                    slide.EndDelay = Convert.ToInt32(txt.Text);
                    break;
            }
        }

        protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddl = sender as DropDownList;
            int originalId = Convert.ToInt32(ddl.Attributes["index"]);
            int newId = Convert.ToInt32(ddl.SelectedValue);
            PhotoGallerySlideInfo item = PhotoGallery[originalId];
            item.OrderIndex = newId;
            if (originalId < newId)
            {
                for (int i = originalId; i < newId; ++i)
                {
                    item = PhotoGallery[i + 1];
                    item.OrderIndex = item.OrderIndex - 1;
                }
            }
            else
            {
                for (int i = newId; i < originalId; ++i)
                {
                    item = PhotoGallery[i];
                    item.OrderIndex = item.OrderIndex + 1;
                }
            }
            BindData();
        }

        private void BindData()
        {
            PhotoGallery.Sort();
            repSlides.DataSource = PhotoGallery;
            repSlides.DataBind();
        }

        private void InitIndexDropDown(DropDownList ddl, int count)
        {
            ddl.Items.Clear();
            for (int i = 0; i < count; ++i)
            {
                ddl.Items.Add(i.ToString());
            }
        }

        private int FindSecureFile(string name)
        {
            DotNetNuke.Services.FileSystem.FileController fc = new DotNetNuke.Services.FileSystem.FileController();
            foreach (System.Data.DataRow dr in fc.GetAllFiles().Select("FileName='" + name + "'"))
            {
                return Convert.ToInt32(dr["FileId"]);
            }
            return -1;
        }

        private string GetImageLocation(Uri uri)
        {
            int id = FindSecureFile(uri.OriginalString);
            string path = string.Format("{0}/{1}", PhotoGallery.BasePath, uri);
            if (id == -1)
            {
                return Page.ResolveUrl(string.Format("{0}{1}/{2}", PortalSettings.HomeDirectory, PhotoGallery.BasePath, uri));
            }
            return string.Format("LinkClick.aspx?fileticket={0}", UrlUtils.EncryptParameter(id.ToString()));
            //return string.Format("LinkClick.aspx?fileid={0}tabid={1}&mid={1}&link={3}", id, TabId, ModuleId, path);
        }

        protected void Update_Click(object sender, System.EventArgs e)
        {
            foreach (PhotoGallerySlideInfo slide in PhotoGallery)
            {
                PhotoGallerySlideController.UpdatePhotoGallerySlide(slide);
            }
            Response.Redirect(Globals.NavigateURL());
        }

        protected void Delete_Click(object sender, System.EventArgs e)
        {

            // Redirect back to the portal
            Response.Redirect(Globals.NavigateURL());
        }

        protected void Cancel_Click(object sender, System.EventArgs e)
        {
            PhotoGallery.Clear();
            PhotoGallery.AddRange(PhotoGallerySlideController.GetPhotoGallerySlides(PhotoGallery.PhotoGalleryId));
            // Redirect back to the portal
            Response.Redirect(Globals.NavigateURL());
        }

        protected void AddSlide_Click(object sender, System.EventArgs e)
        {
            PhotoGallerySlideInfo slideInfo = new PhotoGallerySlideInfo("", "", "");
            slideInfo.PhotoGalleryId = PhotoGallery.PhotoGalleryId;
            slideInfo.OrderIndex = PhotoGallery.Count;
            slideInfo.PhotoGallerySlideId = PhotoGallerySlideController.AddPhotoGallerySlide(slideInfo);
            PhotoGallery.Add(slideInfo);
            BindData();
        }

        protected void RemoveSlide_Click(object sender, System.EventArgs e)
        {
            PhotoGallerySlideInfo slideInfo = PhotoGallery[PhotoGallery.Count - 1];
            PhotoGallerySlideController.DeletePhotoGallerySlide(slideInfo);
            PhotoGallery.Remove(slideInfo);
            BindData();
        }

        protected void repSlides_ItemCommand(object source, RepeaterCommandEventArgs e)
        {

        }
    }
}
